package com.example.management.common.utils

import com.example.management.common.domain.Tree
import com.sun.javafx.robot.impl.FXRobotHelper.getChildren
import sun.management.snmp.jvminstr.JvmThreadInstanceEntryImpl.ThreadStateMap.setState


object BuildTree {

    fun <T> build(nodes: List<Tree<T>>?): Tree<T>? {

        if (nodes == null) {
            return null
        }
        val topNodes = ArrayList<Tree<T>>()

        for (children in nodes) {

            val pid = children.parentId
            if (pid == null || "0" == pid) {
                topNodes.add(children)

                continue
            }

            for (parent in nodes) {
                val id = parent.id
                if (id != null && id == pid) {
                    parent.children.add(children)
                    children.isHasParent = (true)
                    parent.setChildren(true)
                    continue
                }
            }

        }

        var root = Tree<T>()
        if (topNodes.size == 1) {
            root = topNodes[0]
        } else {
            root.id =("-1")
            root.parentId=("")
            root.isHasParent = (false)
            root.setChildren(true)
            root.isChecked = (true)
            root.children = (topNodes)
            root.text = ("顶级节点")
            val state = HashMap<String,Any>(16)
            state.put("opened", true)
            root.state =(state)
        }

        return root
    }

    fun <T> buildList(nodes: List<Tree<T>>?, idParam: String): List<Tree<T>>? {
        if (nodes == null) {
            return null
        }
        val topNodes = ArrayList<Tree<T>>()

        for (children in nodes) {

            val pid = children.parentId
            if (pid == null || idParam == pid) {
                topNodes.add(children)

                continue
            }

            for (parent in nodes) {
                val id = parent.id
                if (id != null && id == pid) {
                    parent.children.add(children)
                    children.isHasParent=(true)
                    parent.setChildren(true)

                    continue
                }
            }

        }
        return topNodes
    }

}